package com.qisu.command;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.qisu.cacheMap.OrderIdCache;
import com.qisu.cacheMap.TimeAndPriceCache;
import com.qisu.converters.Converters;
import com.qisu.model.vo.Gun;
import com.qisu.service.OrderService;

import io.netty.channel.ChannelHandlerContext;

/**
 * 停止充电指令
 * @author li
 *
 */
@Component
public class CMD65534 extends AbstractSinexcelCmd {
	@Autowired private OrderService orderService;
	@Autowired private OrderIdCache orderIdCache;
	@Autowired TimeAndPriceCache timeAndPriceCache;

	@PostConstruct
	@Override
	protected void init() {
		super.init();

		fieldsList.addField(new CommandFieldDef<Integer>(2))
				.addField(new CommandFieldDef<Integer>(2))
				.addField(new CommandFieldDef<String>(40, Converters.strConverter, "单号"));
	}

	@Override
	protected void processCmd(ChannelHandlerContext ctx, byte[] req)  {
		String orderId = fieldsList.getValue("单号");
		Gun PileAndGun = orderService.getOrderPileAndGun(orderId);
		log.info(PileAndGun.toString());
		String pileSerial = PileAndGun.getPileSerial();
		orderIdCache.put(PileAndGun.getKey(), orderId);
		/*HashMap<String, Object> packetData = new HashMap<String, Object>() {
			private static final long serialVersionUID = -2968637679943950197L;

			{
				put("单号", _fieldsList.getValue("单号"));
			}
		};

		_publisher.publish("notify/received/stop-charge", pileSerial);
		_publisher.publish("data/received/stop-charge/" + pileSerial, _json.writeValueAsString(packetData));*/

		// cmd=5
		// @formatter:off
		byte[] p = new byte[] {
			(byte)0xAA, (byte)0xF5,									// signature
			(byte)0x19, (byte)0x00, 								// length
			(byte)0x10, 											// version
			(byte)0x00,												// sequence
			(byte)0x05, (byte)0x00,									// command

			(byte)0x00, (byte)0x00,									// preserved1
			(byte)0x00, (byte)0x00,									// preserved2

			(byte)PileAndGun.getGunNo(),												// gun no
			(byte)0x02,	(byte)0x00, (byte)0x00, (byte)0x00,			// subcommand
			(byte)0x01,												// no. of parameters
			(byte)0x04, (byte)0x00,									// parameters length
			(byte)0x55,	(byte)0x00,	(byte)0x00,	(byte)0x00,			// param
			(byte)0x00												// checksum
		};
		// @formatter:on

		ChannelHandlerContext pileCtx = channelList.get(pileSerial);
		send(pileCtx, p);
		responseClient(ctx);
	}

	@Override
	protected void responseClient(ChannelHandlerContext ctx) {
		log.debug(">>>>>>>>> CTX: " + ctx.channel());
		log.debug("返回APP 200");
		ctx.writeAndFlush("200\n".getBytes());
	}

}
